package com.bert.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.bert.entity.TestDemoEntity;
import com.bert.feign.TestClient;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.RestTemplate;

@RefreshScope //配置自动更新注解
@RestController
@RequestMapping("/test")
public class TestController {

    @Resource
    private RestTemplate restTemplate;
    @Resource
    private TestClient testClient;
    @Resource
    private DiscoveryClient discoveryClient;

    @Value("${test:default}")
    private String test;

    // 获取配置中心配置
    @RequestMapping("/getConfig")
    public String get() {
        return test;
    }

    @GetMapping("/one")
    public String echo(@RequestParam("number") String number) {
        RestClient restClient = RestClient.create();
        restClient.get().uri("")
                .header("", "")
                ;
        return restTemplate.getForObject("http://provider/provider/test/path/" + number, String.class);
    }

    @GetMapping("/notFound")
    public String notFound() {
        String s = testClient.notFound();
        System.out.println("===> " + s);
        return s;
    }

    @GetMapping("/path/{number}")
    @SentinelResource(value = "pathMethod", blockHandler = "blockHandler")
    public String path(@PathVariable String number) {
        return testClient.path(number);
    }

    public String blockHandler(String number, BlockException e){
        return number + "报错了";
    }

    @GetMapping("/param")
    public String param(@RequestParam("a") Integer a, @RequestParam("b") Integer b) {
        if (b == 0) {
            return testClient.param(a);
        }
        return testClient.param(a, b);
    }

    @PostMapping("/post")
    public TestDemoEntity post(@RequestBody TestDemoEntity entity) {
        return testClient.post(entity);
    }

    @GetMapping("/services/{service}")
    public Object client(@PathVariable String service) {
        return discoveryClient.getInstances(service);
    }

    @GetMapping("/services")
    public Object services() {
        return discoveryClient.getServices();
    }



}
